/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CreateOrderPopDialog.java
 *   @Date: 2/3/19 11:27 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.app.trade.ui;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.main.ui.HomeFragment;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.trade.OptionApi;
import io.bhex.sdk.trade.bean.CreateOrderRequest;
import io.bhex.sdk.trade.bean.OptionHoldOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;

public class CreateOrderPopDialog {
    private Context mContext;
    private View mContentView;
    private Dialog bottomDialog;
    private String lastPrice;
    private CoinPairBean coinPairBean;

    private TextView limitedAmountTV;
    private TextView marketAmountTV;
    private TextView limitedPriceTV;
    private TextView get_option_money;
    private int digitBase;
    private int digitAmount;
    private OptionHoldOrderResponse.OptionHoldOrderBean mOptionHoldOrderBean;
    private OnLoadingObserver mObserver;

    public interface OnLoadingObserver{
        void showLoading();
        void hideLoading();
    }

    public CreateOrderPopDialog(Context context, OptionHoldOrderResponse.OptionHoldOrderBean itemModel, OnLoadingObserver observer){
        mContext = context;
        mOptionHoldOrderBean = itemModel;
        mObserver = observer;
    }
    public void ShowDialog(){
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        mContentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_content_circle, null);
        bottomDialog.setContentView(mContentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mContentView.getLayoutParams();
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
        mContentView.setLayoutParams(params);
        initView();
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    private void initView(){
        try {

            if (mOptionHoldOrderBean != null && mContentView != null) {
                String title = "";
                int color = 0;
                if (mOptionHoldOrderBean.position.startsWith("-")) {
                    title = KlineUtils.getOptionBuyOrSellTxt(mContext, false);
                    color = KlineUtils.getBuyOrSellColor(mContext, false);
                } else {
                    title = KlineUtils.getOptionBuyOrSellTxt(mContext, true);
                    color = KlineUtils.getBuyOrSellColor(mContext, true);
                }
                ((TextView) mContentView.findViewById(R.id.order_buy_type)).setText(title);
                ((TextView) mContentView.findViewById(R.id.order_buy_type)).setTextColor(color);
                ((TextView) mContentView.findViewById(R.id.order_coin_name)).setText(mOptionHoldOrderBean.symbolName);
                mContentView.findViewById(R.id.order_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

                ViewPager viewPager = mContentView.findViewById(R.id.createOrderVp);
                SkinTabLayout tab = mContentView.findViewById(R.id.tabText);


                String exchangeId = "";
                coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(mOptionHoldOrderBean.symbolId);
                if (coinPairBean == null) {
                    ToastUtils.showShort(mContext.getResources().getString(R.string.string_data_exception));
                    if (bottomDialog.isShowing()) {
                        bottomDialog.dismiss();
                    }
                    return;
                }
                exchangeId = coinPairBean.getExchangeId();

                QuoteApi.RequestTicker(exchangeId, mOptionHoldOrderBean.symbolId, new SimpleResponseListener<TickerListBean>() {
                    @Override
                    public void onSuccess(TickerListBean response) {

                        List<TickerBean> datas = response.getData();
                        if (datas != null) {
                            for (TickerBean data : datas) {
                                String s = data.getS();
                                if (!TextUtils.isEmpty(s)) {
                                    if (s.equals(mOptionHoldOrderBean.symbolId)) {
                                        lastPrice = data.getC();
                                        limitedPriceTV.setText(NumberUtils.roundFormatDown(lastPrice, digitAmount));
                                    }
                                }
                            }
                        }
                    }
                });

                PointLengthFilter pricePointFilter = new PointLengthFilter();
                PointLengthFilter amountPointFilter = new PointLengthFilter();
                digitBase = NumberUtils.calNumerCount(mContext, coinPairBean.getBasePrecision());
                digitAmount = NumberUtils.calNumerCount(mContext, coinPairBean.getQuotePrecision());

                pricePointFilter.setDecimalLength(digitAmount);
                amountPointFilter.setDecimalLength(digitBase);

                List<View> mViewList = new ArrayList<>();

                View limitedView = LayoutInflater.from(mContext).inflate(R.layout.item_option_create_order_layout, null);
                setShadow(limitedView.findViewById(R.id.edit_price_rela));
                setShadow(limitedView.findViewById(R.id.edit_amount_rela));


                ((TextView) limitedView.findViewById(R.id.edit_price_unit)).setText(mOptionHoldOrderBean.quoteTokenName);

                limitedAmountTV = limitedView.findViewById(R.id.edit_amount);
                limitedAmountTV.setText(String.valueOf(Math.abs(Double.valueOf(mOptionHoldOrderBean.availPosition))));
                limitedAmountTV.setFilters(new InputFilter[]{amountPointFilter});
                limitedAmountTV.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                        //setPriceAbout(s.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        updateTradeAmountOfMoney();
                    }
                });

                limitedPriceTV = limitedView.findViewById(R.id.edit_price);
                limitedPriceTV.setFilters(new InputFilter[]{pricePointFilter});
                limitedPriceTV.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        updateTradeAmountOfMoney();
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                get_option_money = limitedView.findViewById(R.id.get_option_money);
                ((TextView) limitedView.findViewById(R.id.btn_create_order)).setText(R.string.string_option_limited_close);
                limitedView.findViewById(R.id.btn_create_order).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String price = limitedPriceTV.getText().toString().trim();

                        if (TextUtils.isEmpty(price)) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_price));
                            return;
                        }
                        if (Double.valueOf(price) <= 0) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_price));
                            return;
                        }

                        String amount = limitedAmountTV.getText().toString().trim();
                        if (TextUtils.isEmpty(amount)) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_amount));
                            return;
                        }
                        if (Double.valueOf(amount) <= 0) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_amount));
                            return;
                        }
                        if (Double.valueOf(amount) > Math.abs(Double.valueOf(mOptionHoldOrderBean.availPosition))) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_option_over_amount));
                            return;
                        }

                        if (coinPairBean != null) {
                            //最小交易数量
                            String minTradeQuantity = coinPairBean.getMinTradeQuantity();
                            //最小交易额
                            String minTradeAmount = coinPairBean.getMinTradeAmount();

                            String minPricePrecision = coinPairBean.getMinPricePrecision();
                            //最小交易价格
                            if (!TextUtils.isEmpty(minPricePrecision)) {
                                if (NumberUtils.sub(price, minPricePrecision) < 0) {
                                    ToastUtils.showShort(mContext, mContext.getString(R.string.string_min_trade_price, minPricePrecision) + coinPairBean.getQuoteTokenName());
                                    return;
                                }
                            }

                            //最小交易数量
                            if (!TextUtils.isEmpty(minTradeQuantity)) {
                                if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                                    ToastUtils.showShort(mContext, mContext.getString(R.string.string_min_trade_quantity, minTradeQuantity) + mContext.getString(R.string.string_option_unit));
                                    return;
                                }
                            }

                            //最小交易额
                            if (!TextUtils.isEmpty(minTradeAmount)) {
                                if (NumberUtils.sub(String.valueOf(NumberUtils.mul(price, amount)), minTradeAmount) < 0) {
                                    ToastUtils.showShort(mContext, mContext.getString(R.string.string_min_trade_amount, minTradeAmount) + coinPairBean.getQuoteTokenName());
                                    return;
                                }
                            }

                        } else {
                            return;
                        }
                        boolean isBuyMode;
                        if (mOptionHoldOrderBean.position.startsWith("-"))
                            isBuyMode = true;
                        else
                            isBuyMode = false;
                        createOrder(isBuyMode, true, coinPairBean.getExchangeId(), coinPairBean.getSymbolId(), price, amount);
                    }
                });
                mViewList.add(limitedView);


                View marketView = LayoutInflater.from(mContext).inflate(R.layout.item_option_create_order_layout, null);
                ((TextView) marketView.findViewById(R.id.edit_price_unit)).setText(mOptionHoldOrderBean.quoteTokenName);
                marketView.findViewById(R.id.edit_price_rela).setVisibility(View.GONE);
                marketView.findViewById(R.id.priceMarket).setVisibility(View.VISIBLE);
                setShadow(marketView.findViewById(R.id.priceMarket));
                setShadow(marketView.findViewById(R.id.edit_amount_rela));
                marketAmountTV = marketView.findViewById(R.id.edit_amount);
                marketAmountTV.setText(String.valueOf(Math.abs(Double.valueOf(mOptionHoldOrderBean.availPosition))));
                marketAmountTV.setFilters(new InputFilter[]{amountPointFilter});
                ((TextView) marketView.findViewById(R.id.btn_create_order)).setText(R.string.string_option_market_close);
                marketView.findViewById(R.id.btn_create_order).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        String amount = marketAmountTV.getText().toString().trim();
                        if (TextUtils.isEmpty(amount)) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_amount));
                            return;
                        }
                        if (Double.valueOf(amount) <= 0) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_prompt_input_amount));
                            return;
                        }
                        if (Double.valueOf(amount) > Math.abs(Double.valueOf(mOptionHoldOrderBean.availPosition))) {
                            ToastUtils.showShort(mContext, mContext.getString(R.string.string_option_over_amount));
                            return;
                        }

                        if (coinPairBean != null) {
                            //最小交易数量
                            String minTradeQuantity = coinPairBean.getMinTradeQuantity();
                            //最小交易数量
                            if (!TextUtils.isEmpty(minTradeQuantity)) {
                                if (NumberUtils.sub(amount, minTradeQuantity) < 0) {
                                    ToastUtils.showShort(mContext, mContext.getString(R.string.string_min_trade_quantity, minTradeQuantity) + mContext.getString(R.string.string_option_unit));
                                    return;
                                }
                            }

                        } else {
                            return;
                        }
                        boolean isBuyMode;
                        if (mOptionHoldOrderBean.position.startsWith("-"))
                            isBuyMode = true;
                        else
                            isBuyMode = false;
                        createOrder(isBuyMode, false, coinPairBean.getExchangeId(), coinPairBean.getSymbolId(), "", amount);
                    }
                });

                mViewList.add(marketView);

                MultiplePagerAdapter symbolsAdapter = new MultiplePagerAdapter(mViewList);
                viewPager.setAdapter(symbolsAdapter);
                tab.setupWithViewPager(viewPager);
                tab.getTabAt(0).setText(mContext.getString(R.string.string_limited_price));
                tab.getTabAt(1).setText(mContext.getString(R.string.string_market_price));
                tab.setTabMode(TabLayout.MODE_SCROLLABLE);
                tab.setTabGravity(TabLayout.GRAVITY_CENTER);
                CommonUtil.setUpIndicatorWidthByReflex2(tab, 40, 40);


                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
        catch (Exception e){}

    }


    private void updateTradeAmountOfMoney() {

        String amount = limitedAmountTV.getText().toString();
        String price = limitedPriceTV.getText().toString().trim();

            if (TextUtils.isEmpty(price) || TextUtils.isEmpty(amount)) {
                get_option_money.setText(mContext.getString(R.string.string_placeholder));
                return;
            }

            double result = NumberUtils.mul(price, amount);
            String value = /*NumberUtils.roundFormatDown(String.valueOf(result), digitAmount)*/String.valueOf(result);
            String legalMoney = RateDataManager.CurRatePrice(mOptionHoldOrderBean.quoteTokenId, value);
            legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
            get_option_money.setText(value +" " +  mOptionHoldOrderBean.quoteTokenName);
            //get_option_legal_money.setText("≈" + legalMoney);


    }

    public class MultiplePagerAdapter extends PagerAdapter {

        private List<View> mViewList = new ArrayList<>();

        public MultiplePagerAdapter(List<View> views){
            mViewList = views;
        }
        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View symbolItem = null;
            if(position < mViewList.size())
                symbolItem = mViewList.get(position);

            container.addView(symbolItem);
            return symbolItem;// 返回填充的View对象
        }
    }


    private void createOrder(boolean isBuyMode, boolean isLimitedPrice, String exchangeId, String symbol, String price, String amount) {

        CreateOrderRequest requestData = new CreateOrderRequest();
        requestData.exchangeId = exchangeId;
        requestData.symbol = symbol;
        requestData.isBuyMode = isBuyMode;
        requestData.isLimitedPrice = isLimitedPrice;
        requestData.price = price;
        requestData.amount = amount;
        OptionApi.RequestOptionCreateOrder(requestData, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                if(mObserver != null)
                    mObserver.showLoading();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if(mObserver != null)
                    mObserver.hideLoading();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    ToastUtils.showShort(mContext, mContext.getString(R.string.string_create_order_success));
                    bottomDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(mContext,mContext.getString(R.string.string_create_order_failed));
            }
        });
    }

    private void setShadow(View view) {
        ShadowDrawable.setShadowDrawable(view,
//                getResources().getColor(R.color.white),
                PixelUtils.dp2px(2),
                SkinColorUtil.getDark10(mContext),
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }
}
